package com.totobox.apps.activity;

import java.util.Map;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;
import android.widget.MediaController;
import android.widget.VideoView;

import com.totobox.apps.Const;
import com.totobox.apps.R;
import com.totobox.apps.common.DBHelper;
import com.totobox.apps.common.SnowWiFiMonitor;
import com.totobox.apps.common.Util;

public class TotoVodPlayerActivity extends BasicActivity {
	
    public VideoView vv;
    
    public ImageButton btn_normal;
    public ImageButton btn_high;
    public ImageButton btn_bookmark;
    
    public String uri_path = "";
    
    private SnowWiFiMonitor m_SnowWifiMonitor = null;
    
	private int position = 0;
	private int total_position = 0;
	private Map<String,String> vodData;
	
	DBHelper mHelper;
	public SQLiteDatabase db;
	
	public String toto_vod_quality;
	
	public MediaController mediaController;
	
	public String highStream;
	public String normalStream;
	
	public boolean isHighnNormal = false;
	final private int HIGH_DIALOG = 0;
	final private int NORMAL_DIALOG = 1;
	
	//동영상 환경 변경시 이용
	private Handler mHandler = null;
	private HighThread hThread = null;
	private LowThread lThread = null;
	
	private ButtonThread btThread = null;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.toto_player);
        
        vv = (VideoView) findViewById(R.id.toto_video);
        
        btn_normal = (ImageButton) findViewById(R.id.btn_normal);
        btn_high = (ImageButton) findViewById(R.id.btn_high);
        btn_bookmark = (ImageButton) findViewById(R.id.btn_bookmark);
        btn_bookmark.setOnClickListener(this);
        btn_normal.setOnClickListener(this);
        btn_high.setOnClickListener(this);
        
       
        //동영상 화질
    	SharedPreferences pref = TotoVodPlayerActivity.this.getSharedPreferences(Const.APP_NAME, MODE_PRIVATE);
		isHighnNormal = pref.getBoolean("toto_vod_quality", false);
		
        if(Const.dnQueue != null && !Const.dnQueue.isEmpty()){
        	total_position = Const.dnQueue.size();
        	vodData = Const.dnQueue.get(position);
        	
        	normalStream = vodData.get("vcOriginStream");
        	highStream = vodData.get("vcHighStream");
        	
        	uri_path = "rtsp://1.234.52.123/vod/_definst_/21a5165b-6de8-4f52-ae06-8f7c353d0a1a/201206/28/mp4:af11d4ee-74a2-4760-bacc-57580b2fd215";
        	normalStream = uri_path;
        	highStream = uri_path;
        	
        }
        
        //스레드 처리
        hThread = new HighThread();
    	lThread = new LowThread();
    	btThread = new ButtonThread();
		mHandler = new Handler();
		
        mediaController = new MediaController(this);
    	mediaController.setAnchorView(vv);
    	
    	//와이파이면 고화질 , 아니면 일반 화질
    	if(isHighnNormal){
    		//clickedHigh();
			mHandler.postDelayed(hThread, 500);
    	}
    	else if(Util.isWifi(TotoVodPlayerActivity.this)){
    		//clickedHigh();
    		mHandler.postDelayed(hThread, 500);
    	}
    	else{
    		clickedNormal();
    		mHandler.postDelayed(lThread, 500);
    	}
    	
    	//버튼 사라지게 한다.
    	mHandler.postDelayed(btThread, 3000);

    	
    	vv.setOnCompletionListener(new OnCompletionListener(){
    		public void onCompletion(MediaPlayer arg0){

    			if(total_position > (position+1)){
    	        	vodData = Const.dnQueue.get(position);
    	        	normalStream = vodData.get("vcOriginStream");
    	        	highStream = vodData.get("vcHighStream");
    	        }
    			
    			//와이파이면 고화질 , 아니면 일반 화질
    			if(isHighnNormal){
    				mHandler.postDelayed(hThread, 500);
    	    	}
    	    	else if(Util.isWifi(TotoVodPlayerActivity.this)){
    	    		mHandler.postDelayed(hThread, 500);
    	    	}
    	    	else{
    	    		clickedNormal();
    	    		mHandler.postDelayed(lThread, 500);
    	    	}
    		}
    	});

    	vv.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				
				mHandler.removeCallbacks(btThread);
				
				btn_normal.setVisibility(View.VISIBLE);
		        btn_high.setVisibility(View.VISIBLE);
		        btn_bookmark.setVisibility(View.VISIBLE);
		        
		       mHandler.postDelayed(btThread, 3000);
		        
				return false;
			}
		});
    	
    	m_SnowWifiMonitor = new SnowWiFiMonitor(this);
        m_SnowWifiMonitor.setOnChangeNetworkStatusListener(SnowChangedListener);
        
		registerReceiver(m_SnowWifiMonitor, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
		
		mHelper = new DBHelper(this);
    	db=mHelper.getWritableDatabase();
    	
    	//북마크 되어 있는지 체크해서 북마크 버튼 이미지 처리
		Map<String,String> data = Const.dnQueue.get(position);
		
		boolean isLocation = true;
		if (data.get("vcFilePath") == null)
			isLocation = false;
		
    	String[] bind = {isLocation ? data.get("biFileSeq"):data.get("biCursorSeq")};
		Cursor cursor = db.rawQuery("select count(*) count from bookmark where biFileSeq = ?", bind);
    	cursor.moveToFirst();
    	
    	int dataCount = cursor.getInt(0);
    	cursor.close();
    	
    	if (dataCount > 0)
    		btn_bookmark.setPressed(true);
    	else
    		btn_bookmark.setPressed(false);
    }

	@Override
	public void onClick(View v) {
		
		if(v == btn_normal){
			showDialog(NORMAL_DIALOG);
		}
		else if(v == btn_high){
			showDialog(HIGH_DIALOG);
		}
		else if(v == btn_bookmark){
			this.clickedBookmark();
		}
		
	}
	
	/**
	 * 고화질 클릭
	 */
	public void clickedHigh(){
		//super.showText(this, "고화질");
		Uri video = Uri.parse(highStream);
    	vv.setMediaController(mediaController);
    	vv.setVideoURI(video);
    	vv.requestFocus();
    	vv.start();
	}
	
	/**
	 * 일반화질 클릭
	 */
	public void clickedNormal(){
		//super.showText(this, "일반화질");
		Uri video = Uri.parse(normalStream);
    	vv.setMediaController(mediaController);
    	vv.setVideoURI(video);
    	vv.requestFocus();
    	vv.start();
	}
	
	class HighThread implements Runnable {
		public void run() {
			clickedHigh();
		}
	}
	
	class LowThread implements Runnable {
		public void run() {
			clickedNormal();
		}
	}
	
	/**
	 * 버튼을 사라지게 한다.
	 * @author taesu.yoo
	 */
	class ButtonThread implements Runnable {
		public void run() {
			btn_normal.setVisibility(View.INVISIBLE);
	        btn_high.setVisibility(View.INVISIBLE);
	        btn_bookmark.setVisibility(View.INVISIBLE);
		}
	}
	
	/**
	 * 북마크 클릭
	 */
	public void clickedBookmark(){
		Map<String,String> data = Const.dnQueue.get(position);
		
		boolean isLocation = true;
		if (data.get("vcFilePath") == null)
			isLocation = false;
		
		DBHelper helper = new DBHelper(this);
		SQLiteDatabase db = helper.getWritableDatabase();
		
		String[] bind = {isLocation ? data.get("biFileSeq"):data.get("biCursorSeq")};
		Cursor cursor = db.rawQuery("select count(*) count from bookmark where biFileSeq = ?", bind);
    	cursor.moveToFirst();
    	
    	int dataCount = cursor.getInt(0);
    	cursor.close();
    	
    	try{
    		if (dataCount == 0) {
        		ContentValues values = new ContentValues();
        		values.put("biFileSeq", isLocation ? data.get("biFileSeq"):data.get("biCursorSeq"));
        		values.put("iLocationType", isLocation);
        	    values.put("iFileType", "2");
        	    values.put("vcName", data.get("vcName"));
        	    values.put("vcFileKey", data.get("vcFileKey"));
        	    values.put("iFileSize", data.get("iFileSize"));
        	    values.put("vcFilePlayTime", data.get("vcFilePlayTime"));
        	    values.put("vcThumbNailInfo", isLocation ? data.get("vcFilePath"):data.get("vcThumbNailInfo"));
        	    values.put("vcOriginDown", isLocation ? data.get("vcFilePath"):data.get("vcOriginDown"));
        	    values.put("vcHighStream", isLocation ? data.get("vcFilePath"):data.get("vcHighStream"));
        	    values.put("vcLowStream", isLocation ? data.get("vcFilePath"):data.get("vcLowStream"));
        		db.insert("bookmark", null, values);
        		btn_bookmark.setPressed(true);
        		super.showText(this, "즐겨찾기에 추가 되었습니다.");
        	}
        	else {
    			db.delete("bookmark", "biFileSeq = ?", bind);
    			btn_bookmark.setPressed(false);
    			super.showText(this, "즐겨찾기에서 삭제 되었습니다.");
        	}
    	} catch (SQLException e){
    		super.showText(this, "오류가 발생하였습니다.");
    	}
    	
    	db.close();
	}

	@Override
	protected void onDestroy() 
	{
		db.close();
		
		super.onDestroy();
		
		unregisterReceiver(m_SnowWifiMonitor);
	}
	
	SnowWiFiMonitor.OnChangeNetworkStatusListener SnowChangedListener = new SnowWiFiMonitor.OnChangeNetworkStatusListener()
	{
		@Override
		public void OnChanged(int status) 
		{
			switch(status)
			{
				case SnowWiFiMonitor.NETWORK_STATE_CONNECTED:
					//showText(TotoVodPlayerActivity.this, "WI-FI가 연결");
					showDialog(HIGH_DIALOG);
				break;
				
				case SnowWiFiMonitor.NETWORK_STATE_DISCONNECTED:
					//showText(TotoVodPlayerActivity.this, "WI-FI가 종료");
					showDialog(NORMAL_DIALOG);
				break;
				
				case SnowWiFiMonitor.NETWORK_STATE_SUSPENDED:
				break;
				
				case SnowWiFiMonitor.NETWORK_STATE_UNKNOWN:
				break;
	 	
			}
		}
	};
    
	
	@Override
	protected Dialog onCreateDialog (int id) {
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("화질이 변경되면 처음부터 재생됩니다.변경하시겠습니까?").setCancelable(false);
		
		if(id == HIGH_DIALOG){
			builder.setPositiveButton("예", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				//clickedHigh();
				mHandler.postDelayed(hThread, 500);
				dialog.dismiss();
			}
			});
		}
		else{
			builder.setPositiveButton("예", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					//clickedNormal();
					mHandler.postDelayed(lThread, 500);
					dialog.dismiss();
				}
				});
		}
		
		builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int id) {
			dialog.dismiss();
		}
		});
		AlertDialog alert = builder.create();
		alert.show();
		
		return null;
	}
}
